package com.hao.netty.client;

import com.hao.netty.handler.ChatClientInitializer;
import com.hao.netty.listener.ChannelCloseListener;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.CharsetUtil;

import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * TODO
 *
 * @author 97472
 * @version 1.0
 * @date 2021/11/30 15:32
 */
public class ChatClient {

    private final static Integer SERVER_PORT = 6789;

    private final static String SERVER_IP = "127.0.0.1";

    public Channel run(){
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        try {

            Bootstrap bootstrap = new Bootstrap();

            bootstrap.group(eventLoopGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ChatClientInitializer());

            ChannelFuture connectFuture = bootstrap.connect(SERVER_IP, SERVER_PORT).sync();
            connectFuture.addListener(new ChannelFutureListener() {
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    if (channelFuture.isSuccess()){
                        System.out.println("加入群聊成功");
                    }else {
                        System.out.println("加入群聊失败");
                    }
                }
            });

            Channel channel = connectFuture.channel();

            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNextLine()){
                String msg = scanner.nextLine();
                channel.writeAndFlush(msg + "\r\n");
            }
            return channel;
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            eventLoopGroup.shutdownGracefully();
        }
        return null;
    }


    public static void main(String[] args) {
        ChatClient chatClient = new ChatClient();
        Channel channel = chatClient.run();

    }
}
